package org.unit.testmgmt.ui.table;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.unit.testmgmt.ui.table.TableViewerColumn.Columntype;

/**
 * The table viewer columns.
 * 
 * @author Robert Streng
 *
 */
public class TableViewerColumns implements Cloneable {

	private int columnCount = 0;
	private List<TableViewerColumn> columns = new ArrayList<TableViewerColumn>();

	public TableViewerColumns() {
		super();
	}
	
	public TableViewerColumns(List<TableViewerColumn> columns) {
		this.columns = columns;
		this.columnCount = columns.size();
	}
	
	public void addColumn(TableViewerColumn col) {
		col.setIndex(columnCount++);
		columns.add(col);
	}

	public TableViewerColumn getColumn(int ix) {
		return columns.get(ix);
	}

	public List<TableViewerColumn> getColumns() {
		return columns;
	}

	/**
	 * @return columns as string array 
	 */
	public String[] getColumnsStringArray() {
		String[] columnsStrings = new String[columnCount];
		for (int i = 0; i < columnCount; i++) {
			columnsStrings[i] = getColumn(i).getName();
		}
		return columnsStrings;
	}

	public TableViewerColumn getColumn(String name) {
		for (TableViewerColumn column : getColumns())
			if (name.equals(column.getName()))
				return column;

		return null;
	}

	public int size() {
		return columnCount;
	}
	
	/**
	 * Creates the table viewer column.
	 * 
	 * @param elementName
	 * @param signatureSimpleName
	 * @return the table viewer column
	 */
	public static TableViewerColumn createColumn(String elementName,
			String signatureSimpleName) {
		TableViewerColumn column = null;
		int columnStyle = SWT.LEFT;

		signatureSimpleName = signatureSimpleName.toLowerCase();
		
		if (signatureSimpleName.startsWith("string")) {
			column = new TableViewerColumn(elementName, columnStyle,
					Columntype.STRING);
			column.setWidth(100);
		} else if (signatureSimpleName.startsWith("int")
				|| signatureSimpleName.startsWith("integer")) {
			column = new TableViewerColumn(elementName, columnStyle,
					Columntype.INTEGER);
		} else if (signatureSimpleName.startsWith("boolean")) {
			column = new TableViewerColumn(elementName, columnStyle,
					Columntype.BOOLEAN);
		}
		else {
			column = new TableViewerColumn(elementName, columnStyle,
					Columntype.STRING);
		}

		return column;
	}
	
	@Override
	public TableViewerColumns clone() {
		List<TableViewerColumn> copy = new ArrayList<TableViewerColumn>(columns.size());
		
		for (int i = 0; i < columns.size(); i++) {
			copy.add(columns.get(i)); // clone not needed
		}
		
		return new TableViewerColumns(copy);
	}

}
